<template>
  <div class="attendance-app" style="height: 92vh; overflow-y: auto; padding-top: 20px;">
    <!-- 日历区域 -->
    <div class="calendar-container">
      <!-- 顶部日期选择 -->
      <div class="date-selector">
        <el-date-picker v-model="selectedMonth" type="month" placeholder="选择年份和月份" format="YYYY年MM月" value-format="YYYY-MM" @change="loadMonthData" />
      </div>

      <!-- 自定义日历 -->
      <div class="calendar-grid">
        <div v-for="day in calendarDays" :key="day.date" class="calendar-day" :class="{
                  'current-month': day.isCurrentMonth,
                  'today': day.isToday,
                  'selected': day.isSelected,
                  'status-absent': day.status === 5,
                  'status-warning': [0, 3, 4, 6, 7].includes(day.status),
                }" @click="selectDate(day.date)">
          <div class="day-number">{{ day.day }}</div>
        </div>
      </div>
    </div>

    <!-- 考勤记录列表 -->
    <div class="record-list">
      <div class="record-item" v-for="(record, index) in filteredRecords" :key="index">
        <div class="record-left">
          <div class="record-date">{{ formatDate(record.date) }}</div>
          <div class="record-time">
            <span class="time-label">签到：</span>
            <span v-if="record.checkInTime">{{ formatTime(record.checkInTime) }}</span>
            <span v-else class="absent">未签到</span>
          </div>
          <div class="record-time" v-if="record.checkOutTime || showAllRecords">
            <span class="time-label">签退：</span>
            <span v-if="record.checkOutTime">{{ formatTime(record.checkOutTime) }}</span>
            <span v-else class="absent">未签退</span>
          </div>
        </div>
        <div class="record-status">
          <el-tag :type="getStatusTagType(record.status)" size="small" effect="plain">
            {{ getStatusText(record.status) }}
          </el-tag>
        </div>
      </div>
      <div class="no-more-data" v-if="filteredRecords.length === 0">
        <el-divider />
        <div class="no-more-text">没有更多数据了</div>
      </div>
    </div>
  </div>
</template>
    
<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getPersonalAttendance } from "../../api/attendance.js";
import dayjs from "dayjs";

const selectedMonth = ref(dayjs().format("YYYY-MM")); // 默认显示当前月份
const attendanceRecords = ref([]); // 存储所有考勤记录
const filteredRecords = ref([]); // 用于展示的过滤后的记录
const selectedDate = ref(dayjs().format("YYYY-MM-DD")); // 当前选中的日期，默认今天
const showAllRecords = ref(true); // 保留原逻辑，确保签退时间显示

// 状态映射
const statusMap = {
  0: { text: "未知", type: "info" },
  1: { text: "请假", type: "" },
  2: { text: "出差", type: "" },
  3: { text: "正常签到", type: "success" },
  4: { text: "迟到", type: "warning" },
  5: { text: "旷工", type: "danger" },
  6: { text: "早退", type: "warning" },
  7: { text: "部分出勤", type: "warning" },
  8: { text: "正常出勤", type: "success" },
};

// 生成日历天数
const calendarDays = computed(() => {
  const date = dayjs(selectedMonth.value);
  const startOfMonth = date.startOf("month");
  const startDay = startOfMonth.day();
  const daysInMonth = date.daysInMonth();

  const calendarData = [];

  // 上个月的最后几天
  const prevMonth = startOfMonth.subtract(1, "month");
  const daysInPrevMonth = prevMonth.daysInMonth();

  for (let i = startDay - 1; i >= 0; i--) {
    const dayDate = prevMonth.date(daysInPrevMonth - i);
    calendarData.push({
      date: dayDate.format("YYYY-MM-DD"),
      day: dayDate.date(),
      isCurrentMonth: false,
      isToday: dayDate.isSame(dayjs(), "day"),
      isSelected: dayDate.isSame(selectedDate.value, "day"),
      status: null,
    });
  }

  // 当前月的天数
  for (let i = 1; i <= daysInMonth; i++) {
    const dayDate = startOfMonth.date(i);
    const status = attendanceRecords.value.find(
      (record) => record.date === dayDate.format("YYYY-MM-DD")
    )?.status;
    calendarData.push({
      date: dayDate.format("YYYY-MM-DD"),
      day: i,
      isCurrentMonth: true,
      isToday: dayDate.isSame(dayjs(), "day"),
      isSelected: dayDate.isSame(selectedDate.value, "day"),
      status: status,
    });
  }

  // 下个月的前几天
  const nextMonth = startOfMonth.add(1, "month");
  const remainingCells = 42 - calendarData.length;

  for (let i = 1; i <= remainingCells; i++) {
    const dayDate = nextMonth.date(i);
    calendarData.push({
      date: dayDate.format("YYYY-MM-DD"),
      day: i,
      isCurrentMonth: false,
      isToday: dayDate.isSame(dayjs(), "day"),
      isSelected: dayDate.isSame(selectedDate.value, "day"),
      status: null,
    });
  }

  return calendarData;
});

// 获取状态文本和样式
const getStatusText = (status) => statusMap[status]?.text || "未知状态";
const getStatusTagType = (status) => statusMap[status]?.type || "";

// 日期格式化
const formatDate = (dateStr) => dayjs(dateStr).format("YYYY.MM.DD");
const formatTime = (datetimeStr) =>
  dayjs(datetimeStr).format("YY/MM/DD HH:mm:ss");

// 加载月份数据
const loadMonthData = async () => {
  const startDate = dayjs(selectedMonth.value)
    .startOf("month")
    .format("YYYY-MM-DD");
  const endDate = dayjs(selectedMonth.value)
    .endOf("month")
    .format("YYYY-MM-DD");

  try {
    const res = await getPersonalAttendance({
      startDate,
      endDate,
    });

    if (res.flag) {
      attendanceRecords.value = res.result || [];
      filterRecordsByDate(selectedDate.value); // 加载后根据选中日期过滤
    } else {
      ElMessage.warning(res.reason || "加载数据失败");
    }
  } catch (error) {
    ElMessage.error("加载数据失败");
  }
};

// 根据日期过滤记录
const filterRecordsByDate = (date) => {
  filteredRecords.value = attendanceRecords.value.filter(
    (record) => record.date === date
  );
};

// 选择日期
const selectDate = async (date) => {
  selectedDate.value = date; // 更新选中的日期
  selectedMonth.value = dayjs(date).format("YYYY-MM"); // 更新月份
  await loadMonthData(); // 重新加载数据并自动过滤
};

// 初始化加载当前月份数据
onMounted(() => {
  loadMonthData(); // 加载数据并默认显示今天的记录
});
</script>
    
<style scoped>
.attendance-app {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  height: 92vh;
  overflow-y: auto;
}

.calendar-container {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 500px;
  margin-bottom: 20px;
}

.date-selector {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8px;
}

.calendar-day {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  padding: 4px;
}

.calendar-day:hover {
  background-color: #f1f5f9;
}

.calendar-day.current-month {
  color: #334155; /* 当前月份默认黑色 */
}

.calendar-day:not(.current-month) {
  color: #94a3b8; /* 非当前月份灰色 */
}

.calendar-day.today .day-number {
  color: #3b82f6; /* 今天蓝色 */
}

.calendar-day.selected {
  background-color: #e0e7ff; /* 选中背景 */
}

.calendar-day.selected .day-number {
  color: #4f46e5; /* 选中日期颜色 */
}

.calendar-day.status-absent .day-number {
  color: #ef4444; /* 旷工红色 */
}

.calendar-day.status-warning .day-number {
  color: #f59e0b; /* 警告状态橙色 */
}

.day-number {
  font-size: 14px;
  margin-bottom: 2px;
  font-weight: normal; /* 不加粗 */
}

.record-list {
  width: 100%;
  max-width: 500px;
  flex: 1; /* 自适应剩余高度 */
  overflow-y: auto; /* 记录列表内部滚动 */
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background-color: white;
  border-radius: 4px;
  margin-bottom: 6px;
}

.record-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
}

.record-date {
  font-weight: 500;
  font-size: 14px;
  color: #1a1a1a;
}

.record-time {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
}

.time-label {
  color: #999;
  margin-right: 4px;
  min-width: 36px;
}

.record-status {
  margin-left: 12px;
  flex-shrink: 0;
}

.absent {
  color: #f56c6c;
}

.no-more-data {
  text-align: center;
  margin-top: 10px;
  padding: 0 12px;
}

.no-more-data :deep(.el-divider) {
  background-color: #e0e0e0;
}

.no-more-text {
  color: #999;
  font-size: 12px;
  margin-top: -10px;
  background: white;
  display: inline-block;
  padding: 0 10px;
}
</style>